package exhibition.app.nexd.cn.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import butterknife.Bind;
import butterknife.OnClick;
import exhibition.app.nexd.cn.R;
import exhibition.app.nexd.cn.presenter.UserInfoPresenter;
import exhibition.app.nexd.cn.ui.ivew.IUserInfoActivityView;


public class UserInfoActivity extends BaseActivity<UserInfoPresenter> implements IUserInfoActivityView {

    InputMethodManager imm;
    //
//    @Bind(R.id.sv_root_view)
//    ScrollView svRootView;
//    @Bind(R.id.user_btn_submit)
//    Button btnSubmit;
    @Bind(R.id.user_edit_username)
    EditText editUsername;
    @Bind(R.id.user_edit_company)
    EditText editCompany;

    @Override
    public void initView() {
        getSupportActionBar().hide();
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    @Override
    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void initPresenter() {
        presenter = new UserInfoPresenter(this, this);
        presenter.init();
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = this.getCurrentFocus();
            if (isHiddenKeyboard(v, ev)) {
                if (v != null) {
                    hideKeyboard(v.getWindowToken());
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private void hideKeyboard(IBinder token) {
        if (token != null) {
            imm.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private boolean isHiddenKeyboard(View v, MotionEvent ev) {
        if (v != null && v instanceof EditText) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            if (ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom) {
                //点击了EditText就不需要处理
                return false;
            }
        }
        return true;
    }

    @OnClick(R.id.user_btn_submit)
    public void onBtnClick(View v) {
        presenter.insertUser(editUsername.getText().toString(), editCompany.getText().toString());
    }


    @Override
    public void onInsertSuccess() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}
